package framework.mocks
{
    import flash.utils.setTimeout;

    import framework.ArtificialToken;

    import mx.rpc.AbstractOperation;
    import mx.rpc.AbstractService;
    import mx.rpc.AsyncToken;

    public class MockOperation extends AbstractOperation
    {
        public var func:Function;

        public var delay:Number;

        private var tokens:Array = [];

        private var margs:Array = [];

        final public function MockOperation(func:Function, delay:Number = 200, service:AbstractService = null, name:String = null)
        {
            this.func = func;
            this.delay = delay;
            super(service, name);
        }

        override public function send(... args:Array):AsyncToken
        {
            var a:ArtificialToken = new ArtificialToken("result");
            tokens.push(a);
            margs.push(args);
            setTimeout(executeMockFunction, delay);
            return a;
        }

        private function executeMockFunction():void
        {
            var r:* = func.apply(this, margs.pop());
            var a:ArtificialToken = tokens.pop();
            a.resultHandlerForResult(r);
        }
    }
}